package com.deco.service.sys;

import com.deco.dao.domain.table.CmsUser;
import com.deco.domain.vo.constants.CmsConstant;
import com.deco.domain.vo.sys.CmsRoleVo;
import com.deco.logic.sys.CmsRoleLogic;
import com.deco.service.CommonService;
import com.free.common.vo.PageResponseVo;
import com.free.common.vo.PageSearchVo;
import com.free.common.vo.ResultModel;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.deco.domain.vo.sys.CmsUserVo;
import com.deco.logic.sys.CmsUserLogic;

import java.sql.Timestamp;
import java.util.ArrayList;
import java.util.List;

/**
 * <p>
 * 功能概述:
 * </p>
 * <p>
 * 功能详述:
 * </p>
 */
@Service
public class CmsUserService extends CommonService {
    /*========================================================================*
     *                         Public Fields (公共属性)
     *========================================================================*/

    /*========================================================================*
     *                         Private Fields (私有属性)
     *========================================================================*/

    @Autowired
    private CmsUserLogic userLogic;

    @Autowired
    private CmsRoleLogic roleLogic;
    /*========================================================================*
     *                         Construct Methods (构造方法)
     *========================================================================*/

    /*========================================================================*
     *                         Public Methods (公有方法)
     *========================================================================*/

    /**
     * 获得用户
     * @param userName
     * @param password
     * @return
     */
    public CmsUserVo getCmsUser(String userName, String password){
        return userLogic.getCmsUser(userName, password);
    }

    public CmsUserVo getCmsUserById(Integer id){
        return userLogic.getById(id);
    }

    public ResultModel add(CmsUserVo cmsUser){
        return ResultModel.success(userLogic.add(cmsUser));
    }

    public ResultModel delete(CmsUserVo cmsUser){
        ResultModel checkRes = checkUserInfo(cmsUser);
        if(!checkRes.isSuccess()){
            return checkRes;
        }
        int res = userLogic.delete(cmsUser.getId());
        if(res > 0){
            return ResultModel.success();
        }else{
            return ResultModel.failure();
        }
    }

    public ResultModel saveCheck(CmsUserVo cmsUser){
        if(cmsUser.getId() == null || cmsUser.getId() == 0){
            if(StringUtils.isEmpty(cmsUser.getPassword()) || !isStringNumberValid(cmsUser.getPassword(),6, 16)){
                return ResultModel.failure(null, "密码必须为[6~16]个字符(数字、字母)");
            }
            if(StringUtils.isEmpty(cmsUser.getUserName()) || !isStringNumberValid(cmsUser.getUserName(),2, 16)){
                return ResultModel.failure(null, "用户名[2~16]个字符(数字、字母、汉字)");
            }
        }else{
            ResultModel resModel = checkUserInfo(cmsUser);
            if(!resModel.isSuccess()){
                return resModel;
            }
            if(StringUtils.isNotEmpty(cmsUser.getPassword()) && !isStringNumberValid(cmsUser.getPassword(),6, 16)){
                return ResultModel.failure(null,"密码必须为[6~16]个字符(数字、字母)");
            }
        }
        return ResultModel.success();
    }

    public ResultModel save(CmsUserVo cmsUser){
        if(cmsUser.getId() == null || cmsUser.getId() == 0){
            cmsUser.setCreateBy(getCurrentUserId());
            Timestamp dt = getCurrentTimeStamp();
            cmsUser.setCreateTime(dt);
            cmsUser.setUpdateTime(dt);
            cmsUser.setDtmLastLogin(dt);
            cmsUser.setType(CmsConstant.USER_TYPE_GENERAL);
            cmsUser.setLoginCount(0);
            cmsUser = userLogic.add(cmsUser);
            return ResultModel.success(cmsUser);
        }else{
            cmsUser.setUpdateBy(getCurrentUserId());
            cmsUser.setUpdateTime(getCurrentTimeStamp());
            int res = userLogic.update(cmsUser);
            if(res > 0){
                return ResultModel.success();
            }
        }
        return ResultModel.failure();
    }

    public ResultModel checkUpdateuserPwd(CmsUserVo cmsUser){
        if(StringUtils.isEmpty(cmsUser.getPassword()) || StringUtils.isEmpty(cmsUser.getConfirmPassword())){
            return ResultModel.failure(null,"[密码，确认密码]必须输入" );
        }
        if(!cmsUser.getPassword().equals(cmsUser.getConfirmPassword())){
            return ResultModel.failure(null,"[密码，确认密码]不一致" );
        }
        if(!isStringNumberValid(cmsUser.getPassword(), 6, 16)){
            return ResultModel.failure(null,"[密码，确认密码]格式不正确" );
        }
        return ResultModel.success();
    }

    public ResultModel updateUserPwd(CmsUserVo cmsUser){
        cmsUser.setId(getCurrentUserId());
        int res = userLogic.update(cmsUser);
        if(res > 0){
            return ResultModel.success();
        }
        return ResultModel.failure();
    }


    public PageResponseVo<CmsUserVo> selectPageInfoByCmsUser(PageSearchVo<CmsUserVo> condition){
        PageResponseVo<CmsUserVo> respVo = userLogic.selectPageInfoByCmsUser(condition);
        if(respVo.getList() != null){
            respVo.getList().forEach(x->{
                List<CmsRoleVo> roles = roleLogic.getRoleInfos(x.getRoles());
                ArrayList<String> rolenms = new ArrayList<>();
                if(roles == null || roles.size() ==0){
                    x.setRoleName("");
                }else{
                    roles.forEach(j->{
                        rolenms.add(j.getName());
                    });
                    x.setRoleName(StringUtils.join(rolenms,","));
                }
                x.setCreateByName(userLogic.getById(x.getCreateBy()).getUserName());
            });
        }
        return respVo;
    }

    /*========================================================================*
     *                         Private Methods (私有方法)
     *========================================================================*/

    public ResultModel checkUserInfo(CmsUserVo vo){
        CmsUserVo tmp = userLogic.getById(vo.getId());
        if(tmp == null){
            return ResultModel.failure(null, "用户信息不存在");
        }
        if(tmp.getType() == CmsConstant.USER_TYPE_SYSTEM){
            return ResultModel.failure(null, "系统用户不能修改");
        }
        return ResultModel.success();
    }



}
